package com.winchain.chainbill.basic.charge.cmd;

import com.shell.bee.base.utils.StringUtil;
import com.shell.framework.command.CommandContext;
import com.shell.framework.command.ICommand;
import com.winchain.chainbill.basic.charge.po.ValRetBiz;
import com.winchain.chainbill.basic.charge.service.ValComService;
import com.winchain.chainbill.basic.charge.service.ValRetBizService;
import com.winchain.chainbill.basic.charge.vo.ValComVo;
import com.winchain.chainbill.bill.base.po.CbDct;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.biz.Bill;
import java.math.BigDecimal;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class ValRetBizCmd implements ICommand<Bill<CbDct>> {
	@Autowired
	private ValRetBizService valRetBizService;
	@Autowired
	private ValComService valComService;

	public boolean execute(CommandContext<Bill<CbDct>> context) throws Exception {
		CbRec record = ((Bill) context.getSource()).getRec();
		CbDct cbDct = (CbDct) ((Bill) context.getSource()).getSource();

		List<Bill<CbDct>> children = (List) context.getValue("children");
		if ((children != null) && (children.size() > 0)) {
			for (Bill<CbDct> bill : children) {
				if (StringUtil.notEmpty(((CbDct) bill.getSource()).getDctDate())) {
					cbDct = (CbDct) bill.getSource();
					record = bill.getRec();
				}
			}
		}
		if ((cbDct != null) && (cbDct.getDctId() != null)) {
			String bizState = context.getStringValue("valRetBizState");

			ValRetBiz valRetBiz = this.valRetBizService.selectByBizId(cbDct.getDctId());
			if (valRetBiz == null) {
				if (!"D".equals(bizState)) {
					save(cbDct, record);
				}
			} else {
				valRetBiz.setState(bizState);
				this.valRetBizService.updateNotNull(valRetBiz);
			}
		}
		return false;
	}

	private boolean save(CbDct cbDct, CbRec record) {
		String cusId = cbDct.getFinId();
		String grpId = record.getGrpId();
		ValComVo valCom = this.valComService.getDctValComVo(cusId, grpId);
		if ((valCom != null) && ("1".equals(valCom.getValState()))) {
			if ("1".equals(valCom.getPayBy())) {
				return false;
			}
			BigDecimal valAmt = BigDecimal.ZERO;
			if (valCom.getValType().equals("1")) {
				valAmt = cbDct.getDctAmt().multiply(valCom.getValStd()).divide(new BigDecimal("1000"));
			} else if (valCom.getValType().equals("2")) {
				valAmt = cbDct.getDctInt().multiply(valCom.getValStd()).divide(new BigDecimal("100"));
			} else if (valCom.getValType().equals("3")) {
				valAmt = valCom.getValStd();
			}
			String dctDate = cbDct.getDctDate();
			String bizId = cbDct.getDctId();
			String bizType = "0";
			this.valRetBizService.saveServiceFee(bizId, bizType, dctDate, valAmt, valCom);
		}
		return true;
	}
}
